﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MapGenerate
{
	private int Row;
	private int Col;

	public int MaxPropNum;
	public int CurPropNum;

	private Transform WallRoot;

	public List<Vector3> EmptyPostions = new List<Vector3>();
	private List<Wall> WallList = new List<Wall>();
	private List<Wall> canDestroyWallList = new List<Wall>();

	private Vector3 originPos;

	public void Init(Vector3 oriPos)
	{
		originPos = oriPos;

		WallRoot = GameObject.FindWithTag("Root").transform.FindChild("Walls");
	}

	public void GenerateMap(int row, int col)
	{
		Row = row;
		Col = col;
		CurPropNum = 0;
		MaxPropNum = MainGame.Ins.CurLevelInfo.PropList.Count;

		//不可销毁的墙
		for (int i = 0; i < col; i++)
		{
			for (int j = 0; j < row; j++)
			{
				Vector3 pos = new Vector3(i + 0.5f, j + 0.5f, 0);
				if (i == 0 || j == 0 || i == col - 1 || j == row - 1 || (i % 2 == 0 && j % 2 == 0))
				{
					SetWall(pos);
				} else
				{
					EmptyPostions.Add(pos);
				}
			}
		}

		//可销毁的墙
		int total = row * col;
		int RandomSeed = Mathf.Max(Random.Range(total / 15, total / 12), MaxPropNum);
		int wallCount = Mathf.Min(RandomSeed, EmptyPostions.Count);
		while (wallCount>0)
		{
			int randomIndex = Random.Range(0, EmptyPostions.Count);
			SetWall(EmptyPostions[randomIndex], true);
			EmptyPostions.RemoveAt(randomIndex);
			wallCount--;
		}

		//道具
		SetProp();

		EmptyPostions.Clear();
		canDestroyWallList.Clear();
	}

	void SetWall(Vector3 pos, bool canDestroy = false)
	{
		GameObject go = GameRes.Ins.InstantiateImageItem();
		go.transform.position = originPos + pos;
		go.transform.SetParent(WallRoot);
		go.layer = LayerMask.NameToLayer("Wall");
		Wall wall = go.AddComponent<Wall>();
		if (canDestroy)
		{
			go.GetComponent<Image>().sprite = GameRes.Ins.LoadSprite("Sprites/wall2");
			wall.CanDestroy = true;
			canDestroyWallList.Add(wall);
		}
		else
		{
			go.GetComponent<Image>().sprite = GameRes.Ins.LoadSprite("Sprites/wall1");
		}

		WallList.Add(wall);
	}

	public void SetProp()
	{
		while (CurPropNum < MaxPropNum) {
			int randomIndex = Random.Range(0, canDestroyWallList.Count);
			Wall wall = canDestroyWallList[randomIndex];

			wall.SetProp(MainGame.Ins.CurLevelInfo.PropList[CurPropNum]);
			canDestroyWallList.Remove(wall);

			CurPropNum++;
		}
	}

	public void Reset()
	{
		CurPropNum = 0;

		for (int i = 0, length = WallList.Count; i < length; i++)
		{
			Wall wall = WallList[i];
			wall.Clear();
		}
		WallList.Clear();
	}
}
